class WSS {
  ws
  onOpen
  msgMap = {}

  constructor(url) {
    this.ws = new WebSocket(url)

    this.ws.onopen = () => {
      console.log("websocket onopen")
      this.onOpen && this.onOpen();
    }
    this.ws.onerror = message => {
      console.log("websocket onerror")
    }
    this.ws.onmessage = e => {
      // console.log("websocket onmessage", e)
      if (!e.data) {
        return;
      }
      let msgData = JSON.parse(e.data)

      for (const key in this.msgMap) {
        if(msgData.type === key){
          this.msgMap[key] && this.msgMap[key](msgData)
        }
      }

    }
    this.ws.onclose = () => {
      console.log("websocket onclose")
    }
  }

  send(obj) {
    this.ws.send(JSON.stringify(obj))
  }

  subscribe(key, cb) {
    this.msgMap[key] = cb
  }
}